package com.hjk.common.utils.web;

import com.hjk.common.utils.io.IoUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.StringBuilderWriter;
import org.apache.http.entity.ContentType;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItem;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

/**
 * spring文件转换
 * @author huangjunkai
 * @version 1.0
 * @date 2021/04/02
 */
@Slf4j
public class MultipartFileUtils {

    /**
     * File转MultipartFile
     */
    @SneakyThrows
    public static MultipartFile getMultipartFile(File file) {
        FileInputStream fileInputStream = new FileInputStream(file);
        return new MockMultipartFile(file.getName(),file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream);

    }

    /**
     * InputStream转 MultipartFile
     */
    @SneakyThrows
    public static MultipartFile getMultipartFile(String name, InputStream contentStream) {
        return new MockMultipartFile(name,contentStream);
    }

    /**
     * MultipartFile转 string
     */
    @SneakyThrows
    public static String getJsonString(MultipartFile multipartFile) {
        return IOUtils.toString(multipartFile.getInputStream(), StandardCharsets.UTF_8);
    }



}
